package io.modifier.basic.emo.scheme.impl

import android.app.Application
import io.modifier.basic.emo.core.EmoConfig
import io.modifier.basic.emo.scheme.CoreSchemeHandler
import io.modifier.basic.emo.scheme.GeneratedSchemeDefStorageDelegate
import io.modifier.basic.emo.scheme.InterceptorSchemeHandler
import io.modifier.basic.emo.scheme.SchemeClient
import io.modifier.basic.emo.scheme.SchemeDefStorage
import io.modifier.basic.emo.scheme.SchemeHandler
import io.modifier.basic.emo.scheme.SchemeInterceptor

class SchemeClientBuilder(val application: Application) {

    private val interceptors = mutableListOf<SchemeInterceptor>()
    var storage: SchemeDefStorage = GeneratedSchemeDefStorageDelegate
    var blockSameSchemeTimeout = 500L
    fun addInterceptor(interceptor: SchemeInterceptor): SchemeClientBuilder {
        interceptors.add(interceptor)
        return this
    }

    fun build(): SchemeClient {
        val handler = interceptors.asReversed().fold<_, SchemeHandler>(CoreSchemeHandler) { acc, schemeInterceptor ->
            InterceptorSchemeHandler(acc, schemeInterceptor)
        }
        return SchemeClient(
            blockSameSchemeTimeout,
            storage,
            EmoConfig.debug,
            handler,
            AndroidSchemeExecTransactionFactory(application) {
                SchemeTransitionProviders.get(it)
            }
        )
    }
}

fun schemeClient(application: Application, block: SchemeClientBuilder.() -> Unit = {}): SchemeClient {
    val builder = SchemeClientBuilder(application)
    block(builder)
    return builder.build()
}
